package com.cq.hd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.ActiveRedPacketStateEnum;
import com.cq.hd.common.enums.biz.RedPacketTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.vo.BusinessPageVo;
import com.cq.hd.product.api.dto.ActiveRedPacketBillPageDto;
import com.cq.hd.product.api.dto.AvailableRedPacketDto;
import com.cq.hd.product.api.dto.MyPrizeRedPacketBillPageDto;
import com.cq.hd.product.api.dto.PointsRedPacketDto;
import com.cq.hd.product.api.vo.ActiveRedPacketBilListVo;
import com.cq.hd.product.api.vo.ActiveRedPacketBillPageVo;
import com.cq.hd.product.api.vo.MyPrizeRedPacketBillPageVo;
import com.cq.hd.product.po.TbActiveRedPacketBillPo;
import com.cq.hd.product.mapper.TbActiveRedPacketBillMapper;
import com.cq.hd.product.service.TbActiveRedPacketBillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 红包流水表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-23
 */
@Service
public class TbActiveRedPacketBillServiceImpl extends ServiceImpl<TbActiveRedPacketBillMapper, TbActiveRedPacketBillPo> implements TbActiveRedPacketBillService {

    @Autowired
    private TbBusinessApi businessApi;

    @Override
    public Page<ActiveRedPacketBillPageVo> pageReceive(ActiveRedPacketBillPageDto activeRedPacketBillPageDto) {
        PageHelper.startPage(activeRedPacketBillPageDto.getPageNum(), activeRedPacketBillPageDto.getPageSize());
        List<ActiveRedPacketBillPageVo> activeRedPacketBillPageVos = baseMapper.listByDto(activeRedPacketBillPageDto);
        if (!CollectionUtils.isEmpty(activeRedPacketBillPageVos)) {
            LocalDateTime now = LocalDateTime.now();
            for (ActiveRedPacketBillPageVo activeRedPacketBillPageVo : activeRedPacketBillPageVos) {
                if (ActiveRedPacketStateEnum.NO_USE.getValue().equals(activeRedPacketBillPageVo.getState())) {
                    LocalDateTime expireTime = activeRedPacketBillPageVo.getExpireTime();
                    if (!expireTime.isAfter(now)) {
                        activeRedPacketBillPageVo.setState(ActiveRedPacketStateEnum.YES_EXPIRE.getValue());
                    }
                }
            }
        }
        PageInfo<ActiveRedPacketBillPageVo> pageInfo = new PageInfo<>(activeRedPacketBillPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Page<MyPrizeRedPacketBillPageVo> pageMyPrizeRedPacket(MyPrizeRedPacketBillPageDto myPrizeRedPacketBillPageDto) {
        PageHelper.startPage(myPrizeRedPacketBillPageDto.getPageNum(), myPrizeRedPacketBillPageDto.getPageSize());
        List<MyPrizeRedPacketBillPageVo> activeRedPacketBillPageVos = baseMapper.pageMyPrizeRedPacket(myPrizeRedPacketBillPageDto);
        if (!CollectionUtils.isEmpty(activeRedPacketBillPageVos)) {
            LocalDateTime now = LocalDateTime.now();
            for (MyPrizeRedPacketBillPageVo activeRedPacketBillPageVo : activeRedPacketBillPageVos) {
                if (ActiveRedPacketStateEnum.NO_USE.getValue().equals(activeRedPacketBillPageVo.getState())) {
                    LocalDateTime expireTime = activeRedPacketBillPageVo.getExpireTime();
                    if (!expireTime.isAfter(now)) {
                        activeRedPacketBillPageVo.setState(ActiveRedPacketStateEnum.YES_EXPIRE.getValue());
                    }
                }
            }
        }
        PageInfo<MyPrizeRedPacketBillPageVo> pageInfo = new PageInfo<>(activeRedPacketBillPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public ActiveRedPacketBillPageVo getByRedPacketId(Long redPacketId, Long userId) {
        List<TbActiveRedPacketBillPo> tbActiveRedPacketBillPos = baseMapper.selectList(new QueryWrapper<TbActiveRedPacketBillPo>().eq("del_state", 0)
                .eq("red_packet_id", redPacketId).eq("user_id", userId).orderByDesc("receive_time"));
        if (!CollectionUtils.isEmpty(tbActiveRedPacketBillPos)) {
            ActiveRedPacketBillPageVo activeRedPacketBillPageVo = new ActiveRedPacketBillPageVo();
            BeanUtils.copyProperties(tbActiveRedPacketBillPos.get(0), activeRedPacketBillPageVo);
            return activeRedPacketBillPageVo;
        }
        return null;
    }

    @Override
    public ActiveRedPacketBillPageVo getRedPacketBillById(Long id) {
        TbActiveRedPacketBillPo tbActiveRedPacketBillPo = baseMapper.selectById(id);
        if (tbActiveRedPacketBillPo != null && tbActiveRedPacketBillPo.getDelState() == 0) {
            ActiveRedPacketBillPageVo activeRedPacketBillPageVo = new ActiveRedPacketBillPageVo();
            BeanUtils.copyProperties(tbActiveRedPacketBillPo, activeRedPacketBillPageVo);

            return activeRedPacketBillPageVo;
        }
        return null;
    }

    @Override
    public List<ActiveRedPacketBillPageVo> listActiveRedPacketBillByRedPacketIds(List<Long> redPacketIds) {
        return baseMapper.listActiveRedPacketBillByRedPacketIds(redPacketIds);
    }

    @Override
    public List<ActiveRedPacketBillPageVo> listUsedByBusinessId(Long userId, Long businessId) {
        if (businessId == null || businessId <= 0) {
            if (userId == null || userId <= 0) {
                Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
            }

            // 根据userId查询商家id
            BusinessPageVo businessPageVo = businessApi.getByUserId(userId).unpack();
            if (businessPageVo == null) {
                // 如果不是商家，则返回空
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            businessId = businessPageVo.getId();
        }

        List<Integer> activeRedPacketStates = new ArrayList<>();
        activeRedPacketStates.add(ActiveRedPacketStateEnum.YES_UES.getValue());
        activeRedPacketStates.add(ActiveRedPacketStateEnum.YES_VERIFY.getValue());

        return baseMapper.listUsedByBusinessId(businessId, activeRedPacketStates);
    }

    @Override
    public Boolean scanRedPacketBillJob() {
        // 扫描未使用的红包过期时间，如果红包过期时间早于当前时间，则更新为已过期
        List<TbActiveRedPacketBillPo> activeRedPacketBillPos = baseMapper.selectList(new QueryWrapper<TbActiveRedPacketBillPo>()
                .eq("state", ActiveRedPacketStateEnum.NO_USE.getValue()));
        if (CollectionUtils.isEmpty(activeRedPacketBillPos)) {
            return true;
        }

        LocalDateTime now = LocalDateTime.now();
        for (TbActiveRedPacketBillPo activeRedPacketBillPo : activeRedPacketBillPos) {
            LocalDateTime expireTime = activeRedPacketBillPo.getExpireTime();
            if (!expireTime.isAfter(now)) {
                activeRedPacketBillPo.setState(ActiveRedPacketStateEnum.YES_EXPIRE.getValue());
                activeRedPacketBillPo.setUpdateTime(now);
                baseMapper.updateById(activeRedPacketBillPo);
            }
        }

        return true;
    }

    @Override
    public ActiveRedPacketBillPageVo getByActiveIdAndUserId(Long userId, Long activeId) {
        List<TbActiveRedPacketBillPo> tbActiveRedPacketBillPos = baseMapper.selectList(new QueryWrapper<TbActiveRedPacketBillPo>().eq("del_state", 0)
                .eq("active_id", activeId).eq("user_id", userId).orderByDesc("receive_time"));
        if (!CollectionUtils.isEmpty(tbActiveRedPacketBillPos)) {
            ActiveRedPacketBillPageVo activeRedPacketBillPageVo = new ActiveRedPacketBillPageVo();
            BeanUtils.copyProperties(tbActiveRedPacketBillPos.get(0), activeRedPacketBillPageVo);
            return activeRedPacketBillPageVo;
        }
        return null;
    }

    @Override
    public Boolean sendPointsRedPacketBill(PointsRedPacketDto pointsRedPacketDto) {
        LocalDateTime now = LocalDateTime.now();
        Integer validDay = pointsRedPacketDto.getValidDay();
        // 添加红包流水
        TbActiveRedPacketBillPo tbActiveRedPacketBillPo = new TbActiveRedPacketBillPo();
        tbActiveRedPacketBillPo.setBusinessId(pointsRedPacketDto.getBusinessId());
        tbActiveRedPacketBillPo.setActiveId(0L);
        tbActiveRedPacketBillPo.setUserId(pointsRedPacketDto.getUserId());
        tbActiveRedPacketBillPo.setRedPacketId(0L);
        tbActiveRedPacketBillPo.setAmt(pointsRedPacketDto.getAmt());
        tbActiveRedPacketBillPo.setState(ActiveRedPacketStateEnum.NO_USE.getValue());
        tbActiveRedPacketBillPo.setValidDay(validDay);
        tbActiveRedPacketBillPo.setReceiveTime(now);
        tbActiveRedPacketBillPo.setExpireTime(now.plusDays(validDay).with(LocalTime.MAX));
        tbActiveRedPacketBillPo.setCreateTime(now);
        tbActiveRedPacketBillPo.setRedPacketType(RedPacketTypeEnum.POINTS_COUPON.getValue());
        tbActiveRedPacketBillPo.setFullAmount(pointsRedPacketDto.getFullAmount());
        tbActiveRedPacketBillPo.setTitle(pointsRedPacketDto.getTitle());
        return save(tbActiveRedPacketBillPo);
    }

    @Override
    public List<ActiveRedPacketBilListVo> activeAvailableList(AvailableRedPacketDto availableRedPacketDto) {
        return baseMapper.activeAvailableList(availableRedPacketDto);
    }
}
